import axios from 'axios'
import { getCookieLang, getUmsToken } from '@/utils/cookies'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 40000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
  withCredentials: true
})

const headersLang = () => (getCookieLang() === 'zh' ? 'zh_CN' : 'en_US') // 添加切换语言

service.interceptors.request.use(
  config => {
    // console.log('config', config)
    config.showMessage =
      config.showMessage === undefined ? true : config.showMessage
    config.headers['lang'] = headersLang()
    config.headers['iot-app-name'] = 'iot-pipe'

    if (config.data && config.data.isLogin) {
      config.headers['sid'] = sessionStorage.getItem('uuid')
      delete config.data.isLogin
    } else {
      if (
        config.params &&
        (config.params.isLogOut || config.params.isRefresh)
      ) {
        delete config.params.isRefresh
        delete config.params.isLogOut
      } else {
        if (getUmsToken()) {
          config.headers.Authorization = 'Bearer' + ' ' + getUmsToken()
        }
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 是否正在刷新的标记
// let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
// const requests = []

// 返回状态判断(添加响应拦截器)
service.interceptors.response.use(
  async res => {
    // console.log('success-res', res)
    if (res.config.responseType === 'blob') {
      return res
    }
    const { data, status, config } = res
    if (parseInt(status) === 200) {
      // 处理token过期情况
      if (isTokenExpired(res)) {
        handleTokenExpired(config)
      }
      // 处理其他错误码
      if (parseInt(data.code) !== 200) {
        handleErrorResponse(data, config)
      }
      return data
    } else {
      ElMessage({
        message: res.message || (data && data.message) || 'Error',
        type: 'error',
        duration: 3000
      })
      return Promise.reject(
        new Error(res.message || g_t('public.serverErrorTips'))
      )
    }
  },
  error => {
    // console.log('error', error, error.response)
    if (
      error.code === 'ECONNABORTED' &&
      error.message.indexOf('timeout') !== -1
    ) {
      ElMessage({
        message: g_t('route.timeOutTip'),
        type: 'warning'
      })
    } else if (error.response.status === 401) {
      handleTokenExpired()
    } else {
      ElMessage({
        message: error.response.data.message || g_t('public.serverErrorTips'),
        type: 'error',
        duration: 3000
      })
    }
    return Promise.reject(error)
  }
)

// 新增辅助函数
const isTokenExpired = res => {
  return (
    res.code === 1006 ||
    res.data?.code === 1006 ||
    res.data?.data?.code === 1006
  )
}

const handleTokenExpired = async config => {
  await useUserStore().logoutUser()
}

const handleErrorResponse = (response, config) => {
  if ([1010, 401].includes(parseInt(response.code))) {
    useUserStore().logoutUser()
  }
  if (config.showMessage) {
    ElMessage({
      message: response.message || 'Error',
      type: 'error',
      duration: 3000,
      showClose: true
    })
  }
}

export default {
  headersLang,
  get(url, params = {}, option = {}) {
    return service({
      method: 'GET',
      url,
      params,
      option
    })
  },
  post(url, data = {}, option = {}, params = {}) {
    return service({
      method: 'POST',
      url,
      data,
      option,
      params
    })
  },
  download(url, data = {}) {
    service({
      method: 'POST',
      url,
      data,
      responseType: 'blob'
    })
      .then(res => {
        console.log('exportFile', res)
        if (res.data.size === 0) {
          ElMessage({
            message: g_t('public.noReportedData') || 'Error',
            type: 'error',
            duration: 3000
          })
          return
        }
        const link = document.createElement('a')
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        let fileName = res.headers['content-disposition']
        const index = fileName.indexOf('=')
        fileName = fileName.substr(index + 1, fileName.length)
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        ElMessage({
          message: g_rules.zhAndEnShowMsg(fileName, g_t('public.exportTip')),
          type: 'success',
          duration: 3000
        })
        // resolve(res)
      })
      .catch(error => {
        ElMessage({
          message: g_t('public.netConnectError'),
          type: 'error'
        })
        console.log(error)
        // reject(error)
      })
  }
}
